import { observable, action, autorun, toJS } from 'mobx';
import { WeaTableNew, WeaForm } from 'comsMobx';

const { TableStore } = WeaTableNew;
import { message, Modal } from 'antd';
import { ListStore } from './listStore';
import { WeaTools } from 'ecCom';
import * as Apis from '../apis/contractManage';
import * as Apis_Card from '../apis/customercard';
import { crmAddFormRules } from '../util/index';
import { BatchShareStore } from './batchShareStore';
import { WeaLocaleProvider } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

export class ContractManageStore extends ListStore {
    comObj;
	@observable title = getLabel(16260, '合同管理');
    @observable rightMenu =[];
    @observable baseParams = {
      tabType: 'unfinish',
    }
    @observable tabDatas = [];
    @observable dialogPageType = 'view';
    @observable modleSelectTabKey ='1';
    @observable isShowDialog = false;
    @observable hasTab = true;
    @observable canEdit = false;
    @observable status = '0';
    @observable contractId = '';

    @observable infoForm = new WeaForm();
    @observable mainTableInfo = [];
    @observable subTable1Info = [];
    @observable subTable2Info = [];
    @observable subTable3Info = {};
    @observable subTable4Info = {};
    @observable rightMenuInfo = [];

    @observable cardloading = false;

    @observable exchangeList = []; // 相关交流列表
    @observable shareStore = new BatchShareStore();
    @observable shareList = [];
    @observable shareListNew = [];

    @observable verified = false;
    @observable hasRight = false; // 权限
    @observable noExit = false;
    @observable contractShareCondition=[];
    objTable;

	@action
    initDatas=(params = {}) => {
      // this.title = this.title;
      Apis.getContractCondition(params).then((data) => {
        this.condition = data.datas;
        // 根据高级搜索条件初始化form
        this.form && !this.form.isFormInit && this.form.initFormFields(data.datas);
      });
    }
    @action
    initTabs=(params = {}) => {
      Apis.getCrmTabs(params).then((data) => {
        this.tabDatas = data.datas;
      });
    }


    @action
    componentWillMount=(comObj) => {
      this.comObj = comObj;
    }

    @action
    componentDidMount = (objTable) => {
      this.objTable = objTable;
    }
    @action
    getFormCondition = () => {
      Apis.getFormCondition({ showlevel: 1 }).then((data) => {
        if (data.status == 'success') {
          const result = data.data;
          // console.log(result)
          result[0].options.map((o, index) => {
            // console.log(o,index)
            if (o.key == '6') {
              // console.log(result[0].options[index]);
              result[0].options.splice(index, index);
            }
          });
          // console.log(result)
          this.contractShareCondition = result;
        }
      });
    }
	@action
    doSearch=(params = {}) => {
      this.loading = true;
		 // 获取表单的参数值
      const searchParamsAd = this.form.getFormParams();
      const newParams = { ...this.baseParams, ...searchParamsAd, ...params };
      Apis.getContractList(newParams).then((data) => {
        this.tableStore.getDatas(data.sessionkey, params.current || 1);
        this.baseParams = { ...this.baseParams, ...params };
        this.dataKey = data.sessionkey;
        this.loading = false;
      });
    }

    onShowColumn=() => { // 显示定制列
      this.tableStore.setColSetVisible(true);
      this.tableStore.tableColSet(true);
    }
    // 执行完成
    complete=(id, operate) => {
      Apis.complete({ contractId: id }).then((data) => {
        if (typeof window._table !== 'undefined') {
          window._table.reLoad();
        }
        if (operate == 'rightmenu') {
          this.getContractInfo({ contractId: id, operation: 'view' }, '1', true);
        }
      });
    }
    // 签单
    sign = (id, operate) => {
      Apis.sign({ contractId: id }).then((data) => {
        if (typeof window._table !== 'undefined') {
          window._table.reLoad();
        }
        if (operate == 'rightmenu') {
          this.getContractInfo({ contractId: id, operation: 'view' }, '1', true);
        }
      });
    }
    // 提交审批
    approveInfo = (id, operate) => {
      Apis.approveInfo({ contractId: id }).then((data) => {
        if (typeof window._table !== 'undefined') {
          window._table.reLoad();
        }
        if (operate == 'rightmenu') {
          this.getContractInfo({ contractId: id, operation: 'view' }, '1', true);
        }
      });
    }
    // 重新打开
    statusBack=(id, operate) => {
      Apis.statusBack({ contractId: id }).then((data) => {
        if (typeof window._table !== 'undefined') {
          window._table.reLoad();
        }
        if (operate == 'rightmenu') {
          this.getContractInfo({ contractId: id, operation: 'view' }, '1', true);
        }
      });
    }
    // 合同打开
    getContractInfo = (params, key, bool, status) => {
      this.infoForm = new WeaForm();
      this.cardloading = true;
      this.status = status || '';
      this.subTable1Info = {};
      this.subTable2Info = {};
      this.subTable3Info = {};
      this.subTable4Info = {};
      this.rightMenuInfo = [];
      this.status = '';
      this.verified = false;
      this.showContractDialog(key, bool);
      Apis.getContractInfo(params).then((data) => {
        if (data.status == 'success') {
          this.noExit = false;
          this.cardloading = false;
          if (!data.hasright && typeof (data.hasright) !== 'undefined') {
            this.hasRight = false;
            this.verified = true;
          } else {
            this.hasRight = true;
            this.verified = true;
            this.contractId = params.contractId;
            this.dialogPageType = params.operation;

            this.mainTableInfo = data.datas.mainTable;
            this.infoForm && !this.infoForm.isFormInit && this.infoForm.initFormFields(crmAddFormRules(data.datas.mainTable));
            { data.datas.subTable1 && data.datas.subTable1.columnDefine.push({
              title: '', com: [<span />], width: '5%', dataIndex: 'handle', key: 'handle',
            }); }
            { data.datas.subTable2 && data.datas.subTable2.columnDefine.push({
              title: '', com: [<span />], width: '5%', dataIndex: 'handle', key: 'handle',
            }); }
            this.subTable1Info = data.datas.subTable1;
            this.subTable2Info = data.datas.subTable2;
            this.subTable3Info = data.datas.subTable3 || {};
            this.subTable4Info = data.datas.subTable4 || {};
            this.rightMenuInfo = data.datas.rightMenu;
            this.canEdit = data.datas.canEdit;
            this.status = data.datas.status;
          }
        } else {
          // message.error(getLabel(83437,"出现错误！") + data.msgcode);
          this.noExit = true;
        }
      });
    }
    // 编辑
    editInfo = (id) => {
      this.infoForm = new WeaForm();
      this.cardloading = false;
      Apis.getContractInfo({ operation: 'edit', contractId: id }).then((data) => {
        this.cardloading = false;
        this.mainTableInfo = data.datas.mainTable;
        this.infoForm && !this.infoForm.isFormInit && this.infoForm.initFormFields(crmAddFormRules(data.datas.mainTable));
        { data.datas.subTable1 && data.datas.subTable1.columnDefine.push({
          title: '', com: [<span />], width: '5%', dataIndex: 'handle', key: 'handle',
        }); }
        { data.datas.subTable2 && data.datas.subTable2.columnDefine.push({
          title: '', com: [<span />], width: '5%', dataIndex: 'handle', key: 'handle',
        }); }
        this.subTable1Info = data.datas.subTable1;
        this.subTable2Info = data.datas.subTable2;
        this.subTable3Info = {};
        this.subTable4Info = {};
        this.rightMenuInfo = data.datas.rightMenu;
        this.canEdit = data.datas.canEdit;
        this.dialogPageType = 'edit';
      });
    }
    // 批量删除
    deleteContractBatch=(ids) => {
      const _this = this;
      Modal.confirm({
        title: getLabel(15172, '系统提示'),
        content: getLabel(83600, '您确认要删除吗？'),
        okText: getLabel(33703, '确定'),
        cancelText: getLabel(201, '取消'),
        onOk() {
          _this.deleteContract(ids, '');
        },
        onCancel() {},
      });
    }
    // 删除
    deleteContract = (id, operate) => {
      Apis.deleteContract({ contractId: id }).then((data) => {
        if (typeof window._table !== 'undefined') {
          window._table.reLoad();
        }
        if (operate == 'rightmenu') {
          this.closeContractDialog();
        }
      });
    }

    showContractDialog=(key, bool) => {
      this.isShowDialog = true;
      this.modleSelectTabKey = key;
      this.hasTab = bool;
    }

    closeContractDialog=() => {
      this.isShowDialog = false;
      // this.mainTableInfo = [];
      // this.subTable1Info = {};
      // this.subTable2Info = {};
      // this.subTable3Info = {};
      // this.subTable4Info = {};
    }
    // 保存产品数据
    saveContractProduct = (data) => {
      let sum = 0;
      if (data) {
        for (let i = 0; i < data.length; i++) {
          sum += Number(data[i].sumPrice || 0);
        }
      }
      window.e9ChangedFormFieldKey = new Date().getTime();
      this.infoForm.updateFields({ price: { value: sum.toFixed(2) } }, false);// 处理联动主表合同金额
      this.subTable1Info = { ...this.subTable1Info, columnData: data }; // 更新表数据
    }
    // 保存付款方式数据
    saveContractPay = (data) => {
      this.subTable2Info = { ...this.subTable2Info, columnData: data }; // 更新表数据
    }

    // 编辑 新建保存
    saveInfo = (contractId, crmid) => {
      const formParams = this.infoForm.getFormParams();
      const productList = toJS(this.subTable1Info.columnData);
      const payMethodList = toJS(this.subTable2Info.columnData);
      const params = {
        contractId: contractId || '',
        productList: JSON.stringify(productList),
        payMethodList: JSON.stringify(payMethodList),
        ...formParams,
      };

      // 表单验证
      this.infoForm.validateForm().then((f) => {
        const that = this;
        // 产品
        const productrequire = (function () {
          let boole = true;
          boole = that.objTable.refs.productTable.showErrors();

          return boole;
        }());
        // 付款方式
        const payrequire = (function () {
          let boole = true;
          boole = that.objTable.refs.payMethodTable.showErrors();
          return boole;
        }());
        if (f.isValid && productrequire && payrequire) {
          const startdate = `${params.startdate}`;
          const enddate = `${params.enddate}`;
          if (!(startdate > enddate)) {
            if (contractId) { // 有合同id
              this.cardloading = true;
              Apis.saveInfo(params).then((data) => { // 编辑保存
                this.cardloading = false;
                this.getContractInfo({ contractId, operation: 'view' }, '1', true);
                this.doSearch();
              });
            } else { // 新建保存
              this.cardloading = true;
              Apis.saveCreateInfo(params).then((data) => { // 合同新建的保存
                this.cardloading = false;
                this.closeContractDialog();
                this.doSearch();
              });
            }
          } else {
            Modal.warning({
              title: getLabel(15172, '系统提示'),
              content: getLabel(16073, '合同开始日期不能大于合同结束日期！'),
              okText: getLabel(33703, '确定'),
            });
          }
        } else {
          f.showErrors();
        }
      });
    }
    // productSave产品保存
    productSave = (params) => {
      Apis.productSave(params).then((data) => {
        if (data.status == 'success') {
          this.getContractInfo({ contractId: params.contractId, operation: 'edit' }, '1', false);
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }
    payGoodsSave=(params) => {
      Apis.payGoodsSave(params).then((data) => {
        if (data.status == 'success') {
          this.getContractInfo({ contractId: params.contractId, operation: 'edit' }, '1', false);
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }
    payGoodsDelete=(params) => {
      Apis.payGoodsDelete(params).then((data) => {
        if (data.status == 'success') {
          this.getContractInfo({ contractId: params.contractId, operation: 'edit' }, '1', false);
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }
    // 付款操作
    payMethodSave=(params) => {
      Apis.payMethodSave(params).then((data) => {
        if (data.status == 'success') {
          this.getContractInfo({ contractId: params.contractId, operation: 'edit' }, '1', false);
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }
    paySave=(params) => {
      Apis.paySave(params).then((data) => {
        if (data.status == 'success') {
          this.getContractInfo({ contractId: params.contractId, operation: 'edit' }, '1', false);
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }
    payDelete=(params) => {
      Apis.payDelete(params).then((data) => {
        if (data.status == 'success') {
          this.getContractInfo({ contractId: params.contractId, operation: 'edit' }, '1', false);
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }
    changeContractModalTab=(key) => {
      this.modleSelectTabKey = key;
    }
    // 相关交流信息
    getExchangeList =(params, key, bool) => {
      Apis.getExchangeList(params).then((data) => {
        if (data.status == 'success') {
          this.canEdit = data.canEdit;
          this.contractId = params.contractId;
          this.exchangeList = data.datas;
          this.showContractDialog(key, bool);
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }
    // 相关交流保存
    saveDiscuss=(params = {}) => {
      Apis.saveExchange(params).then((data) => {
        if (data.status == 'success') {
          this.getExchangeList({ contractId: params.contractId }, '2', true);
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }
    // 共享设置
    getContractShareList = (params, key, bool) => {
      Apis.getContractShareList(params).then((data) => {
        if (data.status == 'success') {
          this.canEdit = data.canEdit;
          this.contractId = params.contractId;
          this.shareList = data.datas;
          this.shareListNew = data.datas;
          this.showContractDialog(key, bool);
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }
    // 共享设置数据更新
    updateShareList=(data) => {
      this.shareListNew = data;
    }
    // 共享保存
    contractShareSave = (params = {}) => {
      const that = this;
      if (!params.deleteIds) {
        Apis.contractShareSave(params).then((data) => {
          if (data.status == 'success') {
            message.success(getLabel(83551, '保存成功！'));
            that.getContractShareList({ contractId: params.contractId }, '3', true);
          } else {
            message.error(getLabel(83437, '出现错误！') + data.msgcode);
          }
        });
      } else {
        Modal.confirm({
          title: getLabel(15172, '系统提示'),
          content: getLabel(84351, '有数据被删除，是否确定保存?'),
          okText: getLabel(33703, '确定'),
          cancelText: getLabel(201, '取消'),
          onOk() {
            Apis.contractShareSave(params).then((data) => {
              if (data.status == 'success') {
                message.success(getLabel(83551, '保存成功！'));
                that.getContractShareList({ contractId: params.contractId }, '3', true);
              } else {
                message.error(getLabel(83437, '出现错误！') + data.msgcode);
              }
            });
          },
          onCancel() {},
        });
      }
    }

    getContractRightMenu=(params) => {
      Apis_Card.getRightMenuList(params).then((data) => {
        if (data.status == 'success') {
          this.rightMenu = data.datas;
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }


	clearStatus=() => {
	  this.showSearchAd = false;
	  this.baseParams = {
	    tabType: 'unfinish',
	  };
	  this.clearFormFields();
	  this.dialogPageType = 'view';
	  this.modleSelectTabKey = '1';
	  this.isShowDialog = false;
	  this.hasTab = true;
	  this.canEdit = false;
	  this.status = '0';
	  this.contractId = '';
	}
}

